import 'package:stacked/stacked.dart';
import 'package:vista/shared/models/moment_shot.dart';
import 'package:vista/shared/models/user_frame.dart';
import 'package:vista/shared/services/auth_focus.dart';
import 'package:vista/shared/services/post_studio.dart';
import 'package:vista/shared/services/relation_bond.dart';

/// 个人页面视图模型
/// 管理个人页面的数据和状态
class ProfileViewModel extends BaseViewModel {
  final AuthFocus _authFocus;
  final PostStudio _postStudio;
  final RelationBond _relationBond;

  ProfileViewModel(this._authFocus, this._postStudio, this._relationBond);

  UserFrame? _currentUser;
  UserFrame? get currentUser => _currentUser;

  List<MomentShot> _myPosts = [];
  List<MomentShot> get myPosts => _myPosts;

  List<MomentShot> _likedPosts = [];
  List<MomentShot> get likedPosts => _likedPosts;

  int _postCount = 0;
  int get postCount => _postCount;

  int _likeCount = 0;
  int get likeCount => _likeCount;

  int _friendCount = 0;
  int get friendCount => _friendCount;

  Map<String, UserFrame> _userMap = {};
  UserFrame? getUserById(String userId) => _userMap[userId];

  Map<String, int> _likeCountMap = {};
  int getLikeCount(String postId) => _likeCountMap[postId] ?? 0;

  /// 初始化数据
  Future<void> initialize() async {
    setBusy(true);
    try {
      await _loadCurrentUser();
      if (_currentUser != null) {
        await _loadUsers();
        await _loadMyPosts();
        await _loadLikedPosts();
        await _loadStatistics();
        await _loadLikeCounts();
      }
    } finally {
      setBusy(false);
    }
  }

  /// 加载当前用户
  Future<void> _loadCurrentUser() async {
    _currentUser = await _authFocus.getCurrentUser();
    notifyListeners();
  }

  /// 加载我的动态
  Future<void> _loadMyPosts() async {
    if (_currentUser == null) return;
    _myPosts = await _postStudio.getPostsByUser(_currentUser!.id);
    notifyListeners();
  }

  /// 加载用户信息
  Future<void> _loadUsers() async {
    final users = await _authFocus.getUsers();
    _userMap = {for (var user in users) user.id: user};
    notifyListeners();
  }

  /// 加载点赞的动态
  Future<void> _loadLikedPosts() async {
    if (_currentUser == null) return;
    _likedPosts = await _postStudio.getLikedPostsByUser(_currentUser!.id);
    notifyListeners();
  }

  /// 加载点赞数量
  Future<void> _loadLikeCounts() async {
    final allPosts = [..._myPosts, ..._likedPosts];
    for (final post in allPosts) {
      _likeCountMap[post.id] = await _postStudio.getLikeCount(post.id);
    }
    notifyListeners();
  }

  /// 加载统计数据
  Future<void> _loadStatistics() async {
    if (_currentUser == null) return;

    _postCount = _myPosts.length;

    // 计算总点赞数（我所有动态的点赞数之和）
    int totalLikes = 0;
    for (final post in _myPosts) {
      totalLikes += await _postStudio.getLikeCount(post.id);
    }
    _likeCount = totalLikes;

    // 获取朋友数量
    final friendIds = await _relationBond.getFriendsList(_currentUser!.id);
    _friendCount = friendIds.length;

    notifyListeners();
  }

  /// 删除动态
  Future<void> deletePost(String postId) async {
    await _postStudio.deletePost(postId);
    _myPosts.removeWhere((post) => post.id == postId);
    // 重新计算统计数据（包括点赞数）
    await _loadStatistics();
  }

  /// 刷新数据
  Future<void> refresh() async {
    await initialize();
  }
}
